package com.cskaoyan.gateway.controller.user;

import com.mall.user.IUserService;
import com.cskaoyan.gateway.form.user.UserLoginForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码
 */
@RestController
@RequestMapping("/user")
public class CaptchaController {
    public static String ACCESS_TOKEN = "access_token";

    public static String USER_INFO_KEY = "userInfo";

    @Reference(timeout = 3000, check = false)
    IKaptchaService kaptchaService;

    @Reference(timeout = 3000, check = false)
    IUserService userService;


    /**
     * _>通过get的请求给一个cookie附上了验证码
     * 获取验证码
     */
    @Anoymous
    @GetMapping("/kaptcha")
    public ResponseData getKaptchaCode(HttpServletResponse response, HttpServletRequest request) {


        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        //= _>KAPTCHA_UUID+uuid 作为key,以及验证码图片的地址
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.getKaptchaCode(kaptchaCodeRequest);

        if (kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            //_>如果成功拿到验证码
            Cookie cookie = CookieUtil.genCookie("kaptcha_uuid", kaptchaCodeResponse.getUuid(), "/", 60);
            cookie.setHttpOnly(true);
            //_>把验证码的头 和 那个uuid放进去 ,这样就能从redis里面取出验证码
            response.addCookie(cookie);
            //_>这样请求头就会携带这个cookie value为验证码
            return new ResponseUtil<>().setData(kaptchaCodeResponse.getImageCode());
        }
        return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getCode());
    }

    /**
     * post请求可以验证了
     *
     * @param code
     * @param httpServletRequest
     * @return
     */
    @Anoymous
    @PostMapping("/kaptcha")
    public ResponseData validKaptchaCode(@RequestBody String code, HttpServletRequest httpServletRequest) {
        KaptchaCodeRequest request = new KaptchaCodeRequest();
        //_>可以返回cookie中的值,可以得到jwt的结果做一个验证
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        request.setUuid(uuid);
        request.setCode(code);
        KaptchaCodeResponse response = kaptchaService.validateKaptchaCode(request);
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    //先一个get方法来判断登入状态,来找cookie中的token  可以用上面那个方法
    @Anoymous
    @GetMapping("login")
    public ResponseData getLogin(HttpServletRequest httpServletRequest) {
        String access_token = CookieUtil.getCookieValue(httpServletRequest, ACCESS_TOKEN);
        if (StringUtils.isEmpty(access_token)) {
            //没登入返回false
            return ResponseData.getResponse(false, SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage(), 500, null);
        }
        //已登拿到用户信息
        String userInfo = CookieUtil.getCookieValue(httpServletRequest, USER_INFO_KEY);
        if (StringUtils.isEmpty(userInfo)) {
            //没登入返回false
            return ResponseData.getResponse(false, SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage(), 500, null);
        }
        // 从cookie中解密拿到用户名字和id
        // TODO: 2021/12/11 从UserInfo,拿到uid 和 username 返回 格式:uid # username
        String[] userInfos = userInfo.split("#");
        Map<String, Object> result = new HashMap<>();
        result.put("uid", Integer.valueOf(userInfos[0]));
        result.put("username", userInfos[1]);
        return ResponseData.getResponse(true, "success", 200, result);
    }


    //Login的post方法 _>1.验证验证码(似乎已经验证过了)2.验证用户账号与密码(需要一个加密)3.如果成功需要JWT来给一个cookie
    //可以存放JWT的数据 存活时间改成三十分钟
    // Cookie cookie = CookieUtil.genCookie("kaptcha_uuid", kaptchaCodeResponse.getUuid(), "/", 60);
    @Anoymous
    @PostMapping("login")
    public ResponseData PostLogin(@RequestBody UserLoginForm userLoginForm,
                                  HttpServletResponse httpServletResponse,
                                  HttpServletRequest httpServletRequest) {
        //调用,判断验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        //_>可以返回cookie中的值,可以得到jwt的结果做一个验证
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(userLoginForm.getCaptcha());
        KaptchaCodeResponse response = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            //验证码错误
            return ResponseData.getResponse(false, response.getMsg(), 500, response);
        }


        //包装成requst以便验证参数
        UserLoginRequest request = new UserLoginRequest();
        request.setPassword(userLoginForm.getUserPwd());
        request.setUserName(userLoginForm.getUserName());
        //查询结果和放cookie里面值1.jwt的值 2.UserInfo的值
        UserLoginResponse result = userService.userLogin(request);
        //登录失败

        if (SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode().equals(result.getCode())) {
            return ResponseData.getResponse(false, result.getMsg(), 500, result);
        }
        if (SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode().equals(result.getCode())) {
            return ResponseData.getResponse(false, result.getMsg(), 500, result);
        }
        //登入成功,放一个cookid 返回
        Cookie cookieToken = CookieUtil.genCookie(ACCESS_TOKEN, result.getToken(), "/", 1800);
        String userInfo = result.getId() + "#" + result.getUsername();
        Cookie cookieUserInfo = CookieUtil.genCookie(USER_INFO_KEY, userInfo, "/", 1800);
        httpServletResponse.addCookie(cookieToken);
        httpServletResponse.addCookie(cookieUserInfo);
        return ResponseData.getResponse(true, "success", 200, result);
    }


    @GetMapping("/loginOut")
    public ResponseData getLoginOut(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        String token = CookieUtil.getCookieValue(httpServletRequest, ACCESS_TOKEN);
        String userInfo = CookieUtil.getCookieValue(httpServletRequest, USER_INFO_KEY);
        Cookie cookieToken = CookieUtil.genCookie(ACCESS_TOKEN, token, "/", 0);
        Cookie cookieUserInfo = CookieUtil.genCookie(USER_INFO_KEY, userInfo, "/", 0);
        httpServletResponse.addCookie(cookieToken);
        httpServletResponse.addCookie(cookieUserInfo);
        return new ResponseUtil().setData(null);


    }


    @Anoymous
    @PostMapping("/register")
    public ResponseData getRegister(@RequestBody Map<String, String> map, HttpServletRequest httpServletRequest) {
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        //验证码验证
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        String code = kaptchaCodeResponse.getCode();
        if (!code.equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }
        UserRegisterRequest registerRequest = new UserRegisterRequest();
        registerRequest.setUserName(userName);
        registerRequest.setUserPwd(userPwd);
        registerRequest.setEmail(email);
        UserRegisterResponse result = userService.userRegister(registerRequest);
        if (result.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(result);
        }
        return new ResponseUtil<>().setErrorMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());

    }

    @Anoymous
    @GetMapping("/verify")
    public ResponseData getVerify(UserVerifyRequest userVerifyRequest) {

        //1.根据uuid从激活表拿到用户名字

        //2.修改两个表激活和member表的激活状态

        UserVerifyResponse userVerifyResponse = userService.getVerify(userVerifyRequest);
        if (SysRetCodeConstants.SUCCESS.getCode().equals(userVerifyResponse.getCode())) {
            return new ResponseUtil().setData(SysRetCodeConstants.SUCCESS.getMessage());
        }
        return new ResponseUtil().setData(userVerifyResponse.getMsg());
    }

}
